using System;
using System.Data;
using System.Data.Common;
using Microsoft.Data.SqlClient;
using MySql.Data.MySqlClient;
using Npgsql;
using System.Data.SQLite;
using Oracle.ManagedDataAccess.Client;
using SqlInjectionScanner.Config;

namespace SqlInjectionScanner.Utils
{
    /// <summary>
    /// 数据库连接管理器
    /// </summary>
    public class ConnectionManager
    {
        private readonly DatabaseConfig _config;

        public ConnectionManager(DatabaseConfig config)
        {
            _config = config ?? throw new ArgumentNullException(nameof(config));
        }

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns>数据库连接</returns>
        public DbConnection CreateConnection()
        {
            DbConnection connection = _config.DatabaseType switch
            {
                "SqlServer" => new SqlConnection(_config.ConnectionString),
                "MySql" => new MySqlConnection(_config.ConnectionString),
                "PostgreSql" => new NpgsqlConnection(_config.ConnectionString),
                "SQLite" => new SQLiteConnection(_config.ConnectionString),
                "Oracle" => new OracleConnection(_config.ConnectionString),
                _ => throw new NotSupportedException($"不支持的数据库类型: {_config.DatabaseType}")
            };

            connection.Open();
            return connection;
        }

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        /// <returns>连接是否成功</returns>
        public bool TestConnection()
        {
            try
            {
                using var connection = CreateConnection();
                return connection.State == ConnectionState.Open;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取数据库类型对应的参数前缀
        /// </summary>
        /// <returns>参数前缀</returns>
        public string GetParameterPrefix()
        {
            return _config.DatabaseType switch
            {
                "SqlServer" => "@",
                "MySql" => "@",
                "PostgreSql" => "@",
                "SQLite" => "@",
                "Oracle" => ":",
                _ => "@"
            };
        }
    }
}